<?php

class Json {

    public static function encode($struct) {

        if (is_numeric($struct))
            return self::encodeNumeric($struct);

        if (is_string($struct) || is_float($struct))
            return self::encodeString($struct);

        if (is_array($struct))
            return self::encodePhpArray($struct);

		if (is_bool($struct))
            return self::encodeBool($struct);

        return self::encodeString('*ENCODING_ERROR*');
    }

    private static function encodeBool($bool) {
        return ((bool)$bool ? 'true' : 'false');
    }
    private static function encodeString($str) {
        return "'" . self::escape((string)$str) . "'";
    }

    private static function encodeNumeric($num) {
        return ($num + 0);
    }

    private static function encodePhpArray(array $hash) {
        return (array_values($hash) == $hash) ?
            self::encodeArray($hash) :
            self::encodeHash($hash);
    }

    private static function encodeArray(array $array) {
        return '[' . implode(',', array_map(array('self','encode'), $array)) . ']';
    }

    private static function encodeHash(array $hash) {
        //ksort($hash, SORT_STRING);
        $arrPairs = array();
        foreach ($hash as $key => $val) {
            $arrPairs[] = self::encodeString($key) . ':' . self::encode($val);
            //$arrPairs[] = $key . ':' . self::encode($val);
        }
        return '{' . implode(',', $arrPairs) . '}';
    }

	private static function escape($str) {
		return strtr($str,array(
			"\\" => "\\\\",
			"\r" => "\\r",
			"\n" => "\\n",
			"'"  => "\\'",
			'"'  => '\\"',
		));
	}
}


?>